﻿using DAL;
using DianShangHouTai.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace DianShangHouTai.Controllers
{
    public class SystemController : Controller
    {
        ShopContext db = new ShopContext();
        RoleService rs = new RoleService();
        // GET: System系统管理
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Users()
        {
            return View();
        }
        /// <summary>
        /// 调用用户类表数据的方法
        /// </summary>
        /// <returns></returns>
        public ActionResult Useres()
        {
            using (ShopContext db = new ShopContext())
            {
                List<User> users = db.User.Where(p => true).ToList();
                return Content(Pager.PagedData<User>(users, users.Count()));
            }
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public ActionResult User_Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult User_Add(UIUser_Add data)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.User.Add(new User
                    {
                        ZhangHao = data.ZhangHao,
                        PassWord = data.PassWord,
                        XingMin = data.XingMin,
                        DengLuTime = DateTime.Now,
                        XiuGaiSJTime = DateTime.Now
                    });

                    if (db.SaveChanges() > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                    {
                        return Json(new UIResult(false, "未知原因添加失败"));
                    }
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }

            }
            catch (Exception ex)
            {
                return Json(new UIResult(false, ex.Message));
            }

        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult User_Edit(int? Id)
        {
            User ast = db.User.SingleOrDefault(x => x.Id == Id);
            return View(ast);
        }
        [HttpPost]
        public ActionResult User_Edit(UIUser_Add data)
        {
            try
            {

                var obj = db.User.SingleOrDefault(p => p.Id == data.Id);
                obj.ZhangHao = data.ZhangHao;
                obj.XingMin = data.XingMin;
                if (db.SaveChanges() > 0)
                {
                    return Json(new UIResult(true, ""));
                }
                else
                {
                    return Json(new UIResult(false, "未知原因修改失败"));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message));
            }
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult User_del(int? id)
        {
            try
            {
                var obj = db.User.SingleOrDefault(p => p.Id == id);
                List<Role_User> objs = db.Role_User.Where(p => p.UserId == id).ToList();
                if (obj != null)
                {
                    foreach (var item in objs)
                    {
                        db.Role_User.Remove(item);
                    }
                    db.User.Remove(obj);
                }
                if (db.SaveChanges() > 0)
                    return Json(new UIResult(true, "删除成功"));
                else
                    return Json(new UIResult(false, "要删除的数据可能不存在"));
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, "出错了" + ex.Message));
            }
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        [HttpPost]
        public ActionResult User_RePoward(int? id)
        {
            try
            {
                var obj = db.User.SingleOrDefault(p => p.Id == id);
                if (obj.PassWord != "12345")
                {
                    obj.PassWord = "12345";
                }
                if (db.SaveChanges() > 0)
                {
                    return Json(new UIResult(true, "成功重置密码"));
                }
                else
                {
                    return Json(new UIResult(false, "已重置过密码"));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, "出错了:" + ex.Message));
            }
        }
        /// <summary>
        /// 获取所有的校色
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRolesAll()
        {
            var list = rs.Role_User();
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取指定用户的所有信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRolesByUserIdLayUI(int id)
        {
            // db.Configuration.ProxyCreationEnabled = false;
            List<Role_User> list = db.Role_User.Where(p => p.UserId == id).ToList();
            return Json(new { code = 0, msg = "", data = list, count = list.Count() }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 添加用户角色
        /// </summary>
        /// <returns></returns>
        public ActionResult AddUserToRole(int id, string rid)
        {
            string[] arr = rid.Split(',');
            foreach (var item in arr)
            {
                Role_User us = new Role_User
                {
                    UserId = id,
                    RoleId = Convert.ToInt32(item)
                };
                db.Role_User.Add(us);
            }
            db.SaveChanges();
            var list = db.Role_User.Where(p => p.UserId == id).ToList();
            return Json(list);
        }
        /// <summary>
        /// 移除用户角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        public ActionResult RemoveUserFromRole(int id, string rid)
        {
            string[] arr = rid.Split(',');
            foreach (var item in arr)
            {
                int rrd = Convert.ToInt32(item);
                Role_User ur = db.Role_User.SingleOrDefault(p => p.UserId == id && p.RoleId == rrd);
                db.Role_User.Remove(ur);
            }
            db.SaveChanges();
            var list = db.Role_User.Where(p => p.UserId == id).ToList();
            return Json(list);
        }
        /// <summary>
        /// 角色管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Role()
        {

            return View();
        }
        /// <summary>
        /// 查询角色的页面方法
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            List<Role> users = db.Role.Where(p => true).ToList();
            return Content(Pager.PagedData<Role>(users, users.Count()));
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <returns></returns>
        public ActionResult Role_Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Role_Add(UIRole data)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Role.Add(new Role
                    {
                        RoleName = data.RoleName,
                        Weight = 0

                    });
                    int r = db.SaveChanges();
                    if (r > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                        return Json(new UIResult(false, "未知原因添加失败"));
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message));
            }
        }
        /// <summary>
        /// 角色编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Role_Edit(int? id)
        {
            Role ats = db.Role.SingleOrDefault(x => x.Id == id);
            return View(ats);
        }
        [HttpPost]
        public ActionResult Role_Edit(UIRole data)
        {
            try
            {
                if (ModelState.IsValid)//obj在形成对象时，是否全部符合注解中的规定
                {
                    var obj = db.Role.SingleOrDefault(x => x.Id == data.Id);
                    obj.RoleName = data.RoleName;
                    obj.Weight = data.Weight;
                    if (db.SaveChanges() > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                    {
                        return Json(new UIResult(false, "错误："));
                    }
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message));
            }
        }
        /// <summary>
        /// 角色删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Role_Del(int id)
        {
            try
            {
                var obj = db.Role.SingleOrDefault(p => p.Id == id);
                List<Role_User> objs = db.Role_User.Where(p => p.RoleId == id).ToList();
                if (obj != null)
                {
                    foreach (var item in objs)
                    {
                        db.Role_User.Remove(item);
                    }
                    db.Role.Remove(obj);
                }
                if (db.SaveChanges() > 0)
                    return Json(new UIResult(true, ""));
                else
                    return Json(new UIResult(false, "要删除的数据可能已经不存在"));
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, "出错了：" + ex.Message));
            }
        }
        /// <summary>
        /// 角色批量删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Pubdel(int Id)
        {
            String sql = string.Format("delete from Role where [Id] in ({0})", Id, DateTime.Now);
            try
            {
                var obj = db.Role.SingleOrDefault(p => p.Id == Id);
                List<Role_User> objs = db.Role_User.Where(p => p.RoleId == Id).ToList();
                if (obj != null)
                {
                    foreach (var item in objs)
                    {
                        db.Role_User.Remove(item);
                    }
                    db.Role.Remove(obj);
                }
                int res = db.Database.ExecuteSqlCommand(sql);
                if (res > 0)
                {
                    return Json(new UIResult(true, ""));

                }
                else
                {
                    return Json(new UIResult(false, "要删除的数据已经不可能存在"));
                }

            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message));
            };
        }
        /// <summary>
        /// 模块设置的视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdateModulees(int Id)
        {
            List<int> list = RoleModuleService.GetModuleIdList(Id);
            ViewBag.RMRoleId = Id;
            ViewBag.IdList = list;
            return View();
        }
        /// <summary>
        /// 获取所有的模块
        /// </summary>
        /// <returns></returns>
        public ActionResult GetModuleAll()
        {
            StringBuilder stringbuleder = new StringBuilder();
            List<Module> list = ModuleService.GetList(p => p.MParentId == 0).ToList();
            foreach (var item in list)
            {
                stringbuleder.Append("{\"title\":\"" + item.MModuleName + "\" ,\"id\":" + item.MId + ",\"spread\":true,\"children\":[");
                List<Module> childrenlist = ModuleService.GetList(p => p.MParentId == item.MId).ToList();
                int i = 1;
                foreach (var children in childrenlist)
                {
                    if (i++ == childrenlist.Count)
                    {
                        stringbuleder.Append("{\"title\": \"" + children.MModuleName + "\" ,\"id\":" + children.MId + "}");
                    }
                    else
                    {
                        stringbuleder.Append("{\"title\": \"" + children.MModuleName + "\" ,\"id\":" + children.MId + "},");
                    }
                }
                stringbuleder.Append("]},");
            }
            return Content("[" + stringbuleder.ToString().TrimEnd(',') + "]");
        }
        /// <summary>
        /// 修改模块方法
        /// </summary>
        /// <param name="RMModuleId"></param>
        /// <param name="RMRoleId"></param>
        /// <returns></returns>
        public ActionResult GUpdateModule(string RMModuleId, int RMRoleId)
        {
            String sql = string.Format("delete from RoleModule where  RMRoleId={0}", RMRoleId);
            int r = db.Database.ExecuteSqlCommand(sql);
            int res = 0;
            string[] arr = RMModuleId.Split(',');//分割字符串得到数组

            for (int i = 0; i < arr.Length; i++)
            {
                String sql1 = string.Format("insert into RoleModule values({0},{1})", RMRoleId, int.Parse(arr[i]));
                int a = db.Database.ExecuteSqlCommand(sql1);
                res += a;
            }
            if (res > arr.Length - 1)
            {
                return Json(new UIResult(true, "修改成功"));
            }
            else
            {
                return Json(new UIResult(false, "修改失败"));
            }
        }
        /// <summary>
        /// 模块管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Moduel()
        {
            return View();
        }
        /// <summary>
        /// 获取模块
        /// </summary>
        /// <returns></returns>
       public ActionResult GetModule()
        {
            List<Module> users = db.Module .Where(p => true).ToList();
            return Content(Pager.PagedData<Module>(users, users.Count()));
        }
        /// <summary>
        /// 添加模块
        /// </summary>
        /// <returns></returns>
        public ActionResult AddModule()
        {
            return View();
        }
        /// <summary>
        /// 添加模块的方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddModule(UIModule module)
        {
           try
            {
                if (ModelState.IsValid)
                {

                    db.Module.Add(new Module
                    {
                        MModuleName = module.MModuleName,
                        MControllerName = "sss",
                        MActionName = "sss",
                        MParentId = module.MParentId

                    });
                    int r = db.SaveChanges();
                    if (r > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                        return Json(new UIResult(false, "未知原因添加失败"));
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message ));
            }
        }
        /// <summary>
        /// 角色编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdateModule(int? id)
        {
            Module ats = db.Module.SingleOrDefault(x => x.MId == id);
            return View(ats);
        }
        [HttpPost]
        public ActionResult UpdateModule(UIModule data)
        {
            try
            {
                if (ModelState.IsValid)//obj在形成对象时，是否全部符合注解中的规定
                {
                    var obj = db.Module.SingleOrDefault(x => x.MId == data.MId);
                    obj.MModuleName = data.MModuleName;
                    obj.MControllerName = data.MControllerName;
                    obj.MActionName = data.MActionName;
                    obj.MParentId = data.MParentId;
                    if (db.SaveChanges() > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                    {
                        return Json(new UIResult(false, "错误："));
                    }
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, ex.Message));
            }
        }
        /// <summary>
        /// 模块删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelModule(int id )
        {
            try
            {
                var obj = db.Module.SingleOrDefault(p => p.MId == id);
                    db.Module .Remove(obj);
                if (db.SaveChanges() > 0)
                    return Json(new UIResult(true, "删除成功"));
                else
                    return Json(new UIResult(false, "要删除的数据可能不存在"));
            }
            catch (Exception ex)
            {
                return Json(new UIResult(false, "出错了" + ex.Message));
            }
        }
    }
}